package com.ecut.property_project.controller;

import com.ecut.property_project.model.Sms;
import com.ecut.property_project.model.character.Account;
import com.ecut.property_project.service.base.BaseCompanyService;
import com.ecut.property_project.service.impl.AccountServiceImpl;
import com.ecut.property_project.service.impl.UserServiceImpl;
import com.ecut.property_project.utils.JWTUtils;
import com.ecut.property_project.utils.Result;
import com.ecut.property_project.utils.enumType.SmsType;
import com.github.qcloudsms.SmsSingleSender;
import com.github.qcloudsms.SmsSingleSenderResult;
import com.github.qcloudsms.httpclient.HTTPException;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.json.JSONException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.nio.charset.StandardCharsets;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/account")
//顶格controller写此controller关于哪个数据操作，内部方法连接命名再修改
public class AccountController {

    @Autowired
    private AccountServiceImpl accountService;

    @Autowired
    private UserServiceImpl userService;

    @Autowired
    private BaseCompanyService baseCompanyService;

    @PostMapping("/register")
    public Result register(@RequestBody Map<String, String> data) {
        String tel = data.get("tel");
        String password = data.get("password");
        String username = data.get("username");
        return accountService.register(tel, password,username);
    }

    @RequestMapping("/login")
    public Result login(@RequestBody Map<String, String> data) throws UnsupportedEncodingException{
        String tel = data.get("tel");
        String password = data.get("password");
        String company = data.get("company");
        System.out.println(company);
        Account account = accountService.accountLogin(tel,password);
        String com = baseCompanyService.selectByName(company);
        System.out.println(com);
        if(com == null) {
            return Result.fail("没有该公司");
        }
        if(account == null){
            return Result.fail("账户或密码错误");
        }
        String token = JWTUtils.sign(tel, password);
        return Result.succ(200,"success",token);
    }


    @RequestMapping("/logout")
    public Result logout() {

        Subject subject = SecurityUtils.getSubject();
        System.out.println(subject);
        System.out.println(subject.isAuthenticated());
        if (subject.isAuthenticated()) {
            subject.logout();
            return Result.succ(200,"登出成功",null);
        }
        return Result.fail("登出失败");
    }

    @RequestMapping("/updatePassword")
    public Result updatePassword(@RequestBody Map<String, String> data) throws UnsupportedEncodingException {
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        Account oldAccount = accountService.accountLogin(account.getTel(), data.get("oldPassword"));
        if(oldAccount == null) {
            return Result.fail("原密码错误");
        }
        account.setPassword(data.get("newPassword"));
        accountService.updateAccount(account);
        String token = JWTUtils.sign(account.getTel(), account.getPassword());
        return Result.succ(200,"success",token);
    }
    // 通过短信验证，修改密码, 重新登录 获取token
    @RequestMapping("/updatePasswordBySms")
    public Result updatePasswordBySms(@RequestBody Map<String, String> data) throws UnsupportedEncodingException{
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        account.setPassword(data.get("newPassword"));
        accountService.updateAccount(account);
        String token = JWTUtils.sign(account.getTel(), account.getPassword());
        return Result.succ(200,"success",token);
    }

    // 重新绑定手机号,返回新的token
    @RequestMapping("/updateTel")
    public Result updateTel(@RequestBody Map<String, String> data) throws UnsupportedEncodingException {
        Account account = (Account) SecurityUtils.getSubject().getPrincipal();
        account.setTel(data.get("newTel"));
        userService.updateUserTel(account.getTel(), account.getId());
        accountService.updateAccount(account);
        String token = JWTUtils.sign(account.getTel(), account.getPassword());
        return Result.succ(200,"success",token);
    }

    // 发送验证码接口
    @RequestMapping(value = "/sendCode")
    public Result sendCode(@RequestBody Map<String,String> map) throws HTTPException, IOException, JSONException {
        // 默认为2分钟;
        Sms sms = new Sms();
        sms.setPhoneNumber(map.get("tel"));
        sms.setCode(Sms.getSmsCode());

        System.out.println(sms);

        String[] params = {sms.getCode(), sms.getMin()}; //短信中的参数
        SmsSingleSender sender = new SmsSingleSender( Integer.parseInt(SmsType.APPID.getValue()) , SmsType.APPKEY.getValue());
        SmsSingleSenderResult result = sender.sendWithParam("86",sms.getPhoneNumber(),Integer.parseInt(SmsType.TEMPLATEID.getValue()) ,
                params,SmsType.SMSSIGN.getValue(), "","");
        System.out.println(result);

        return Result.succ(200,"success", sms.getCode());
    }

    @RequestMapping("/loginBySms")
    public Result loginBySms(@RequestBody Map<String,String> map) throws UnsupportedEncodingException{
        Account account = accountService.getAccount(map.get("tel"));
        if(account == null) {
            return Result.fail(400,"账号未注册",null);
        }
        String token = JWTUtils.sign(account.getTel(),account.getPassword());
        return Result.succ(200,"success",token);
    }

    // shrio,controller,错误提示
    @RequestMapping(path = "/unauthorized/{message}")
    public Result unauthorized(@PathVariable String message) throws UnsupportedEncodingException {
//        System.out.println(message);
        return Result.fail(URLDecoder.decode(message, "utf-8"));
    }

}
